package org.jeecg.modules.settle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.cmbCloudDirectLink.utils.GENKey;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.api.IManageBaseAPI;
import org.jeecg.modules.business.service.ICaishuiBusinessService;
import org.jeecg.modules.business.service.ICaishuiCompanySetService;
import org.jeecg.modules.business.service.ISigningMemberService;
import org.jeecg.modules.manage.entity.*;
import org.jeecg.modules.manage.vo.ServiceFeeVo;
import org.jeecg.modules.manage.vo.SigningMemberImportVo;
import org.jeecg.modules.manage.vo.TaskSettleImportVo;
import org.jeecg.modules.settle.mapper.CaishuiTaskSettleItemMapper;
import org.jeecg.modules.settle.mapper.CaishuiTaskSettleMapper;
import org.jeecg.modules.settle.service.ICaishuiTaskSettleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 任务结算
 * @Author: yfkj
 * @Date:   2023-02-20
 * @Version: V1.0
 */
@Service
public class CaishuiTaskSettleServiceImpl extends ServiceImpl<CaishuiTaskSettleMapper, CaishuiTaskSettle> implements ICaishuiTaskSettleService {

	@Resource
	private CaishuiTaskSettleMapper caishuiTaskSettleMapper;
	@Resource
	private CaishuiTaskSettleItemMapper caishuiTaskSettleItemMapper;
	@Autowired
	private ISigningMemberService iSigningMemberService;
	@Autowired
	private ICaishuiBusinessService iCaishuiBusinessService;
	@Resource
	private IManageBaseAPI iManageBaseAPI;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(CaishuiTaskSettle caishuiTaskSettle, List<CaishuiTaskSettleItem> caishuiTaskSettleItemList) {
		caishuiTaskSettleMapper.insert(caishuiTaskSettle);
		if(caishuiTaskSettleItemList!=null && caishuiTaskSettleItemList.size()>0) {
			for(CaishuiTaskSettleItem entity:caishuiTaskSettleItemList) {
				//外键设置
				entity.setMainId(caishuiTaskSettle.getId());
				caishuiTaskSettleItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(CaishuiTaskSettle caishuiTaskSettle,List<CaishuiTaskSettleItem> caishuiTaskSettleItemList) {
		caishuiTaskSettleMapper.updateById(caishuiTaskSettle);

		//1.先删除子表数据
		caishuiTaskSettleItemMapper.deleteByMainId(caishuiTaskSettle.getId());

		//2.子表数据重新插入
		if(caishuiTaskSettleItemList!=null && caishuiTaskSettleItemList.size()>0) {
			for(CaishuiTaskSettleItem entity:caishuiTaskSettleItemList) {
				//外键设置
				entity.setMainId(caishuiTaskSettle.getId());
				caishuiTaskSettleItemMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		caishuiTaskSettleItemMapper.deleteByMainId(id);
		caishuiTaskSettleMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			caishuiTaskSettleItemMapper.deleteByMainId(id.toString());
			caishuiTaskSettleMapper.deleteById(id);
		}
	}

	/**
	 * 结算单导入
	 *
	 * @param request
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> importExcel(HttpServletRequest request,String uploadType) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//获取请求过来的文件对象
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();// 获取上传文件对象
		if (fileMap.entrySet().size() > 1) throw new JeecgBootException("单次只能上传一个文件！");
		// 直接获取当前用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		// 错误信息
		List<String> errorMessage = new ArrayList<>();
		BigDecimal totalAmount = new BigDecimal(0.00),successAmount = new BigDecimal(0.00),failAmount = new BigDecimal(0.00);//总金额、成功金额、失败金额
		int totalNum = 0,successNum = 0,failNum = 0;//总笔数、成功笔数、失败笔数
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				/**1、读取导入的文件到list列表*/
				List<TaskSettleImportVo> importVoList = ExcelImportUtil.importExcel(file.getInputStream(), TaskSettleImportVo.class, params);
				if(oConvertUtils.listIsEmpty(importVoList)){
					throw new JeecgBootException("请上传结算单数据！");
				}else if(importVoList.size() > 1000){
					throw new JeecgBootException("单次导入数据不能超过1000条，如有空白行请先删除多余空白行！");
				}

				//按照编码长度排序
//				Collections.sort(importVoList);

				/**2、查询商户的发放临界值*/
				//商户信息
				CaishuiBusiness business = iCaishuiBusinessService.getById(loginUser.getCurBusiness());
				if(oConvertUtils.isEmpty(business)){
					throw new JeecgBootException("商户信息错误！");
				}
				//商户银行信息
				Map<String, String> b_params = new HashMap<>();
				b_params.put("businessId",loginUser.getCurBusiness());
				b_params.put("companyId",loginUser.getCurCompany());
				b_params.put("type","1");
				CaishuiBusinessBank businessBank = iCaishuiBusinessService.queryBusinessBank(b_params);
				if(oConvertUtils.isEmpty(businessBank)){
					throw new JeecgBootException("商户银行信息错误！");
				} else if(businessBank.getTaxRate() <= 0){
					throw new JeecgBootException("税率错误！");
				}

				/**3、创建任务结算实体*/
				CaishuiTaskSettle taskSettle = new CaishuiTaskSettle();
				taskSettle.setBusinessId(loginUser.getCurBusiness());
				taskSettle.setCompanyId(loginUser.getCurCompany());
				taskSettle.setTenantId(business.getTenantId());
				taskSettle.setUserId(business.getUserId());
				taskSettle.setChannelBusinessId(business.getChannelBusinessId());
				taskSettle.setOrderNo(FillRuleUtil.OrderNumberRule("XF",""));
				taskSettle.setName(file.getOriginalFilename());
				taskSettle.setPayName(businessBank.getAccountName());
				taskSettle.setPayAccount(businessBank.getMainAccount());
				taskSettle.setPaySubUnit(businessBank.getSubAccountId());
				taskSettle.setSettleDoc("/");//先虚拟设置一个值
				taskSettle.setTaxRate(businessBank.getTaxRate());
				taskSettle.setTaxRateTwo(businessBank.getTaxRateTwo());
				caishuiTaskSettleMapper.insert(taskSettle);

				//循环处理导入数据
				int submitStatus = 1;//提交状态：1-直接发放，2-审核发放，3-禁止发放
				BigDecimal totalFee = new BigDecimal(0.00);//服务费总额
				for (int i = 0; i < importVoList.size(); i++) {
					TaskSettleImportVo taskSettleImportVo = importVoList.get(i);
					if(oConvertUtils.isEmpty(taskSettleImportVo.getName())){
						continue;
					}

					try {
						/**4、创建任务结算详情实体*/
						//判断该信息是否已添加
						long count = caishuiTaskSettleItemMapper.selectCount(QueryGenerator.initQueryWrapper(new CaishuiTaskSettleItem(),null)
								.lambda().eq(CaishuiTaskSettleItem::getMainId,taskSettle.getId())
								.and((wrapper) -> wrapper.eq(CaishuiTaskSettleItem::getIdCard,taskSettleImportVo.getIdCard())
										.or().eq(CaishuiTaskSettleItem::getBankCard,taskSettleImportVo.getBankCard())));
						if(count > 0){
							failNum++;
							errorMessage.add("第 " + (i + 4) + " 行：下发人员【"+taskSettleImportVo.getName()+"】信息已存在，已忽略导入。");
							continue;
						}
						//判断该人才是否存在
						CaishuiMember caishuiMember = iSigningMemberService.getOne(QueryGenerator.initQueryWrapper(new CaishuiMember(),null).lambda()
								.eq(CaishuiMember::getBusinessId,loginUser.getCurBusiness()).eq(CaishuiMember::getCompanyId,loginUser.getCurCompany())
								.eq(CaishuiMember::getIdCard,taskSettleImportVo.getIdCard()).eq(CaishuiMember::getName,taskSettleImportVo.getName())
								.eq(CaishuiMember::getStatus,1).eq(CaishuiMember::getSigningStatus,2));
						if(oConvertUtils.isEmpty(caishuiMember)){
							failNum++;
							errorMessage.add("第 " + (i + 4) + " 行：下发人员【"+taskSettleImportVo.getName()+"】不存在或已冻结或未签约，已忽略导入。");
							continue;
						}else {
							//更新签约人才银行卡信息
							caishuiMember.setBankCardType("OTHERBANK");//暂时默认为银行卡
							caishuiMember.setBankCardAccount(taskSettleImportVo.getBankCard());
							iSigningMemberService.updateById(caishuiMember);
						}

						//判断下发人员最低下发金额
						if (taskSettleImportVo.getMoney() < business.getLowestAmount()) {
							failNum++;
							errorMessage.add("第 " + (i + 4) + " 行：下发人员【"+taskSettleImportVo.getName()+"】下发金额不符合规定(最低下发金额："+business.getLowestAmount()+")，已忽略导入。");
							continue;
						}

						//添加详情
						CaishuiTaskSettleItem item = new CaishuiTaskSettleItem();
						BeanUtils.copyProperties(taskSettleImportVo, item);
						item.setTenantId(business.getTenantId());
						item.setMainId(taskSettle.getId());
						item.setCode(String.format("%08d", (i+1)));
						item.setType("OTHERBANK");//TODO 目前只支持下发银行卡
						//判断是否存在禁止下发人员
						if(business.getStopAmount() > 0 && taskSettleImportVo.getMoney() >= business.getStopAmount()
								&& submitStatus < 3){
							submitStatus = 3;
						} else if(business.getCheckAmount() > 0 && taskSettleImportVo.getMoney() >= business.getCheckAmount()
								&& submitStatus < 2){
							//判断是否存在审核下发人员
							submitStatus = 2;
						}
						//计算服务费
						//double serviceFee = BigDecimal.valueOf(item.getMoney()).multiply(BigDecimal.valueOf(businessBank.getTaxRate())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
						if (oConvertUtils.isEmpty(businessBank.getTaxRateTwo())) {
							businessBank.setTaxRateTwo(businessBank.getTaxRate());
						}
						Result<ServiceFeeVo> serviceFeeVoResult = iManageBaseAPI.handleServiceFee(item.getIdCard(), item.getMoney(), businessBank.getTaxRate(), businessBank.getTaxRateTwo());
						if (serviceFeeVoResult.isSuccess()) {
							ServiceFeeVo serviceFeeVo = serviceFeeVoResult.getResult();
							if (serviceFeeVo.getServiceFee() <= 0) {
								failNum++;
								errorMessage.add("第 " + (i + 4) + " 行：计算下发金额服务费出错，已忽略导入。");
								continue;
							}
							item.setServiceFee(serviceFeeVo.getServiceFee());
							item.setServiceFeeDiffer(serviceFeeVo.getServiceFeeDiffer());
						} else {
							failNum++;
							errorMessage.add("第 " + (i + 4) + " 行：计算下发金额服务费出错，已忽略导入。");
							continue;
						}
						caishuiTaskSettleItemMapper.insert(item);

						//计算成功数据
						successAmount = successAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
						totalFee = totalFee.add(new BigDecimal(item.getServiceFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
						successNum++;
					}catch (Exception e) {
						failNum++;
						errorMessage.add("第 " + (i + 4) + " 行：下发人员【"+taskSettleImportVo.getName()+"】数据有误，请仔细检查所有数据是否正确。");
					}
				}

				//计算总数据
				totalAmount = failAmount.add(successAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
				totalNum = successNum;

				/**5、上传结算单到服务器*/
				String savePath = fileUpload(file,loginUser.getCurBusiness(),uploadType);
				if(oConvertUtils.isEmpty(savePath)){
					throw new JeecgBootException("上传文件发生错误！");
				}

				/**6、更新任务结算实体*/
				//如果导入总数据为0，则删除任务结算记录
				if(totalNum == 0 && oConvertUtils.isNotEmpty(taskSettle)){
					caishuiTaskSettleMapper.deleteById(taskSettle);
				}else {
					//更新
					taskSettle.setSettleDoc(savePath);
					taskSettle.setTotalAmount(totalAmount);
					taskSettle.setTotalNum(totalNum);
//					taskSettle.setSuccessAmount(successAmount);
//					taskSettle.setSuccessNum(successNum);
//					taskSettle.setFailAmount(failAmount);
//					taskSettle.setFailNum(failNum);
					taskSettle.setServiceFee(totalFee.doubleValue());
					taskSettle.setSubmitStatus(submitStatus);
					caishuiTaskSettleMapper.updateById(taskSettle);
				}
			} catch (Exception e) {
				errorMessage.add("发生异常：" + e.getMessage());
				throw new JeecgBootException("导入异常！");
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		/**返回数据*/
		if(failNum==0){
			return Result.ok("全部导入成功！共【" + totalNum + "】笔、【" + totalAmount + "】元！");
		}else {
			JSONObject result = new JSONObject();
			result.put("msg", "总共导入：【" + (successNum+failNum) + "】笔；" +
					"成功导入：【" + successNum + "】笔、【" + successAmount + "】元；" +
					"错误导入：【" + failNum + "】笔。");
//			String fileUrl = PmsUtil.saveErrorTxtByList(errorMessage, "userImportExcelErrorLog");
//			int lastIndex = fileUrl.lastIndexOf(File.separator);
//			String fileName = fileUrl.substring(lastIndex + 1);
//			result.put("fileUrl", "/sys/common/static/" + fileUrl);
//			result.put("fileName", fileName);
			Result res = Result.ok(result);
			res.setCode(201);
			res.setMessage("文件导入成功，但有错误。");
			return res;
		}
	}

	/**
	 * 结算单数据列表导入
	 *
	 * @param jsonArray
	 * @param fileName
	 * @param savePath
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> handleImportList(JSONArray jsonArray, String fileName, String savePath) {
		// 直接获取当前用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		//商户信息
		CaishuiBusiness business = iCaishuiBusinessService.getOne(new LambdaQueryWrapper<CaishuiBusiness>()
				.select(CaishuiBusiness::getTenantId,CaishuiBusiness::getUserId,CaishuiBusiness::getChannelBusinessId,
						CaishuiBusiness::getCheckAmount,CaishuiBusiness::getStopAmount,CaishuiBusiness::getLowestAmount)
				.eq(CaishuiBusiness::getId,loginUser.getCurBusiness()));
		if(oConvertUtils.isEmpty(business)){
			throw new JeecgBootException("商户信息错误！");
		}
		//商户银行信息
		Map<String, String> b_params = new HashMap<>();
		b_params.put("businessId",loginUser.getCurBusiness());
		b_params.put("companyId",loginUser.getCurCompany());
		b_params.put("type","1");
		CaishuiBusinessBank businessBank = iCaishuiBusinessService.queryBusinessBank(b_params);
		if(oConvertUtils.isEmpty(businessBank)){
			throw new JeecgBootException("商户银行信息错误！");
		} else if(businessBank.getTaxRate() <= 0){
			throw new JeecgBootException("税率错误！");
		}

		/**创建任务结算实体*/
		CaishuiTaskSettle taskSettle = new CaishuiTaskSettle();
		taskSettle.setBusinessId(loginUser.getCurBusiness());
		taskSettle.setCompanyId(loginUser.getCurCompany());
		taskSettle.setTenantId(business.getTenantId());
		taskSettle.setUserId(business.getUserId());
		taskSettle.setChannelBusinessId(business.getChannelBusinessId());
		taskSettle.setOrderNo(FillRuleUtil.OrderNumberRule("XF",""));
		taskSettle.setName(fileName);
		taskSettle.setPayName(businessBank.getAccountName());
		taskSettle.setPayAccount(businessBank.getMainAccount());
		taskSettle.setPaySubUnit(businessBank.getSubAccountId());
		taskSettle.setSettleDoc(savePath);
		taskSettle.setTaxRate(businessBank.getTaxRate());
		taskSettle.setTaxRateTwo(businessBank.getTaxRateTwo());
		caishuiTaskSettleMapper.insert(taskSettle);

		// 错误信息
		List<String> errorMessage = new ArrayList<>();
		BigDecimal totalAmount = new BigDecimal(0.00),successAmount = new BigDecimal(0.00),failAmount = new BigDecimal(0.00);//总金额、成功金额、失败金额
		int totalNum = 0,successNum = 0,failNum = 0;//总笔数、成功笔数、失败笔数
		int submitStatus = 1;//提交状态：1-直接发放，2-审核发放，3-禁止发放
		BigDecimal totalFee = new BigDecimal(0.00);//服务费总额
		//循环处理导入数据
		for (int i = 0; i < jsonArray.size(); i++) {
			/**导入数据处理*/
			TaskSettleImportVo taskSettleImportVo = JSONObject.parseObject(JSON.toJSON(jsonArray.get(i)).toString(), TaskSettleImportVo.class);
			if(oConvertUtils.isEmpty(taskSettleImportVo.getName()) || oConvertUtils.isEmpty(taskSettleImportVo.getPhone())
					|| oConvertUtils.isEmpty(taskSettleImportVo.getIdCardType()) || oConvertUtils.isEmpty(taskSettleImportVo.getIdCard())
					|| oConvertUtils.isEmpty(taskSettleImportVo.getBankCard()) || oConvertUtils.isEmpty(taskSettleImportVo.getMoney())){
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：导入数据错误（非选填字段为空），已忽略导入。");
				continue;
			} else if (!CommonUtils.isValidMobile(taskSettleImportVo.getPhone())) {//手机号码验证
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：导入数据错误（手机号码格式错误），已忽略导入。");
				continue;
			} else if( taskSettleImportVo.getIdCardType() != 1){
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：导入数据错误（目前只支持身份证验证），已忽略导入。");
				continue;
			} else if( taskSettleImportVo.getMoney() <= 0){
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：导入数据错误（下发金额不能小于等于0），已忽略导入。");
				continue;
			}

			/**创建任务结算详情实体*/
			//判断该信息是否已添加
			long count = caishuiTaskSettleItemMapper.selectCount(QueryGenerator.initQueryWrapper(new CaishuiTaskSettleItem(),null)
					.lambda().eq(CaishuiTaskSettleItem::getMainId,taskSettle.getId())
					.and((wrapper) -> wrapper.eq(CaishuiTaskSettleItem::getIdCard,taskSettleImportVo.getIdCard())
							.or().eq(CaishuiTaskSettleItem::getBankCard,taskSettleImportVo.getBankCard())));
			if(count > 0){
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：下发人员【"+taskSettleImportVo.getName()+"】信息已存在，已忽略导入。");
				continue;
			}
			//判断该人才是否存在
			CaishuiMember caishuiMember = iSigningMemberService.getOne(QueryGenerator.initQueryWrapper(new CaishuiMember(),null).lambda()
					.eq(CaishuiMember::getBusinessId,loginUser.getCurBusiness()).eq(CaishuiMember::getCompanyId,loginUser.getCurCompany())
					.eq(CaishuiMember::getIdCard,taskSettleImportVo.getIdCard()).eq(CaishuiMember::getName,taskSettleImportVo.getName())
					.eq(CaishuiMember::getStatus,1).eq(CaishuiMember::getSigningStatus,2));
			if(oConvertUtils.isEmpty(caishuiMember)){
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：下发人员【"+taskSettleImportVo.getName()+"】不存在或已冻结或未签约，已忽略导入。");
				continue;
			}else if (oConvertUtils.isNotEmpty(caishuiMember.getBankCardAccount())){
				//更新签约人才银行卡信息
				caishuiMember.setBankCardType("OTHERBANK");//暂时默认为银行卡
				caishuiMember.setBankCardAccount(taskSettleImportVo.getBankCard());
				iSigningMemberService.updateById(caishuiMember);
			}

			//判断下发人员最低下发金额
			if (taskSettleImportVo.getMoney() < business.getLowestAmount()) {
				failNum++;
				failAmount = failAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
				errorMessage.add("第 " + (i + 1) + " 行：下发人员【"+taskSettleImportVo.getName()+"】下发金额不符合规定(最低下发金额："+business.getLowestAmount()+")，已忽略导入。");
				continue;
			}

			//添加详情
			CaishuiTaskSettleItem item = new CaishuiTaskSettleItem();
			item.setName(taskSettleImportVo.getName());
			item.setIdCardType(taskSettleImportVo.getIdCardType());
			item.setIdCard(taskSettleImportVo.getIdCard());
			item.setPhone(taskSettleImportVo.getPhone());
			item.setType("OTHERBANK");//TODO 目前只支持下发银行卡
			item.setBankCard(taskSettleImportVo.getBankCard());
			item.setBankName(taskSettleImportVo.getBankName());
			item.setAccountName(taskSettleImportVo.getAccountName());
			item.setMoney(taskSettleImportVo.getMoney());
			item.setRemark(taskSettleImportVo.getRemark());
			item.setTenantId(business.getTenantId());
			item.setMainId(taskSettle.getId());
			item.setCode(String.format("%08d", (i+1)));
			//判断是否存在禁止下发人员
			if(business.getStopAmount() > 0 && taskSettleImportVo.getMoney() >= business.getStopAmount() && submitStatus < 3){
				submitStatus = 3;
			} else if(business.getCheckAmount() > 0 && taskSettleImportVo.getMoney() >= business.getCheckAmount() && submitStatus < 2){
				//判断是否存在审核下发人员
				submitStatus = 2;
			}

			//计算服务费
			//double serviceFee = BigDecimal.valueOf(item.getMoney()).multiply(BigDecimal.valueOf(businessBank.getTaxRate())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
			if (oConvertUtils.isEmpty(businessBank.getTaxRateTwo())) {
				businessBank.setTaxRateTwo(businessBank.getTaxRate());
			}
			Result<ServiceFeeVo> serviceFeeVoResult = iManageBaseAPI.handleServiceFee(item.getIdCard(), item.getMoney(), businessBank.getTaxRate(), businessBank.getTaxRateTwo());
			if (serviceFeeVoResult.isSuccess()) {
				ServiceFeeVo serviceFeeVo = serviceFeeVoResult.getResult();
				if (serviceFeeVo.getServiceFee() <= 0) {
					failNum++;
					errorMessage.add("第 " + (i + 4) + " 行：计算下发金额服务费出错，已忽略导入。");
					continue;
				}
				item.setServiceFee(serviceFeeVo.getServiceFee());
				item.setServiceFeeDiffer(serviceFeeVo.getServiceFeeDiffer());
			} else {
				failNum++;
				errorMessage.add("第 " + (i + 4) + " 行：计算下发金额服务费出错，已忽略导入。");
				continue;
			}
			caishuiTaskSettleItemMapper.insert(item);

			//计算成功数据
			successAmount = successAmount.add(new BigDecimal(taskSettleImportVo.getMoney())).setScale(2,BigDecimal.ROUND_HALF_UP);
			totalFee = totalFee.add(new BigDecimal(item.getServiceFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
			successNum++;
		}

		//计算总数据
		totalAmount = failAmount.add(successAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
		totalNum = successNum;

		/**更新任务结算实体*/
		//如果导入总数据为0，则删除任务结算记录
		if(totalNum == 0 && oConvertUtils.isNotEmpty(taskSettle)){
			caishuiTaskSettleMapper.deleteById(taskSettle);
		}else {
			//更新
			taskSettle.setTotalAmount(totalAmount);
			taskSettle.setTotalNum(totalNum);
			taskSettle.setServiceFee(totalFee.doubleValue());
			taskSettle.setSubmitStatus(submitStatus);
			caishuiTaskSettleMapper.updateById(taskSettle);
		}

		//返回数据
		Map<String, Object> result = new HashMap<>();
		result.put("errorMessage",errorMessage);
		result.put("totalAmount",totalAmount);
		result.put("successAmount",successAmount);
		result.put("failAmount",failAmount);
		result.put("totalNum",totalNum);
		result.put("successNum",successNum);
		result.put("failNum",failNum);
		return result;
	}

	public String fileUpload(MultipartFile file, String businessId, String uploadType){
		String savePath = "";//数据库保存路径
		String bizPath = "uploadFile/taskSettle/" + businessId + "/" + DateUtils.sdf8.format(new Date());//文件的文件夹标记
		//根据配置的文件上传类型选择文件上传
		try {
			if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
//					 savePath = this.uploadLocal(file,bizPath,2);//本地文件上传
			}else if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
				savePath = MinioUtil.upload(file,bizPath,null);//minio文件上传
			}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
				savePath = OssBootUtil.upload(file,bizPath);//阿里云OSS文件上传
			}
		}catch (Exception e){
			log.error("文件上传失败：" + e.getMessage());
		}
		return savePath;
	}

}
